package com.uyayo.oms.blog.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.ParentNotFoundException;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.message.model.Result;
import com.uyayo.oms.blog.vo.BlogCategoryVO;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.blog.entity.BlogCategory;
import com.uyayo.blog.model.BlogCategoryCondition;
import com.uyayo.blog.service.BlogCategoryService;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.service.MemberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 
 * Title: BlogCategoryController
 * Description:资源的Controller
 *
 * @author 乐乐科技.胡逢君
 * @date 2017-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/oms/blog/category")
public class BlogCategoryController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final BlogCategoryService blogCategoryService;

	private final ParamBiz paramBiz;

	private  final  MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final MemberService memberService;

	@Autowired
	public BlogCategoryController(BlogCategoryService blogCategoryService, ParamBiz paramBiz, MessageSource messageSource, DozerBeanMapper dozerBeanMapper, MemberService memberService) {
		this.blogCategoryService = blogCategoryService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
		this.memberService = memberService;
	}

	/**
	 * 获得资源treeGrid
	 */
	@ResponseBody
	@RequestMapping("tree")
	@MethodName(value="博客管理->博客类目管理->查询",type=2)
	public List<BlogCategory> tree(BlogCategoryCondition blogCategoryCondition) {

		if(!Objects.isNull(blogCategoryCondition.getUsername())){
			Member member = memberService.getMemberByUsername(blogCategoryCondition.getUsername());
			if(member!=null){
				blogCategoryCondition.setMemberId(member.getId());
			}
		}
		return blogCategoryService.selectBlogCategory(blogCategoryCondition);
	}

	/**
	 * 获得资源treeGrid
	 */
	@ResponseBody
	@RequestMapping("treeGrid")
	@MethodName(value="博客管理->博客类目管理->查询",type=2)
	public List<BlogCategory> treeGrid(BlogCategoryCondition blogCategoryCondition) {

		if(!Objects.isNull(blogCategoryCondition.getUsername())){
			Member member = memberService.getMemberByUsername(blogCategoryCondition.getUsername());
			if(member!=null){
				blogCategoryCondition.setMemberId(member.getId());
			}
		}
		if(Objects.isNull(blogCategoryCondition.getParentId())){
			blogCategoryCondition.setParentId(0L);
		}
        return blogCategoryService.selectBlogCategory(blogCategoryCondition);
	}


	/**
	 * 列表首页
	 */
	@RequestMapping("index")
	@MethodName(value="记事管理->博客类目管理")
	public ModelAndView index(ModelAndView modelAndView,String parentId,String username) {
		modelAndView.addObject("parentId",parentId);
		modelAndView.addObject("username",username);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/category/index");
		return modelAndView;
	}


	/**
	 * 查看资源信息
	 */
	@RequestMapping("view")
	public ModelAndView view(ModelAndView modelAndView,Long id) {
		BlogCategory blogCategory  = blogCategoryService.selectByKey(id);
		Member member = memberService.getMemberById(blogCategory.getMemberId());
		BlogCategoryVO blogCategoryVO = dozerBeanMapper.map(blogCategory,BlogCategoryVO.class);
		blogCategoryVO.setUsername(member.getUsername());
		modelAndView.addObject("blogCategory",blogCategoryVO);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/category/view");
		return modelAndView;
	}

	/**
	 * 添加资源信息
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView add(ModelAndView modelAndView) {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/category/add");
		return modelAndView;
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@MethodName(value="博客管理->博客类目管理->添加",type=2)
	public Result add(@Validated BlogCategoryVO blogCategoryVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(blogCategoryVO.getUsername());
			if(member==null){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			BlogCategory blogCategory = dozerBeanMapper.map(blogCategoryVO,BlogCategory.class);
			blogCategory.setMemberId(member.getId());
			blogCategory.setHasChildren(false);
			blogCategory.setCreateBy(sysUser.getLoginname());
			blogCategory.setCreateTime(new Date());
			blogCategoryService.saveBlogCategory(blogCategory);
		} catch (ParentNotFoundException e){
			String message = messageSource.getMessage(ResultMsgEnum.PARENT_NOT_FOUND.getKey(),new Object[]{}, request.getLocale());
			logger.warn(message,e.getMessage());
			return Result.error(ResultMsgEnum.PARENT_NOT_FOUND.code(),message);
        }catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
        }
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}

	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	public ModelAndView update(ModelAndView modelAndView,Long id) {
		BlogCategory blogCategory = blogCategoryService.selectByKey(id);
		Member member = memberService.getMemberById(blogCategory.getMemberId());
		BlogCategoryVO blogCategoryVO = dozerBeanMapper.map(blogCategory,BlogCategoryVO.class);
		blogCategoryVO.setUsername(member.getUsername());
		modelAndView.addObject("blogCategory",blogCategoryVO);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"blog/category/update");
		return modelAndView;
	}

	/**
	 * 更新
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@MethodName(value="博客管理->博客类目管理->修改",type=2)
	public Result update(@Validated BlogCategoryVO blogCategoryVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			if (StringUtils.isEmpty(blogCategoryVO.getId())) {
                String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
                logger.warn(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
            }

			if (blogCategoryVO.getParentId() != null && Objects.equals(blogCategoryVO.getId(), blogCategoryVO.getParentId())) {
				String message = messageSource.getMessage(ResultMsgEnum.PARENT_SELF_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.PARENT_SELF_ERROR.code(),message);
			}

			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(blogCategoryVO.getUsername());
			if(member==null){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			BlogCategory blogCategory = dozerBeanMapper.map(blogCategoryVO,BlogCategory.class);
			blogCategory.setMemberId(member.getId());
			blogCategory.setUpdateBy(sysUser.getLoginname());
			blogCategory.setUpdateTime(new Date());
			int updateCount = blogCategoryService.updateBlogCategory(blogCategory);
			if(updateCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.SAVE_FAIL.getKey(),new Object[]{}, request.getLocale());
                logger.warn(message);
				return Result.error(ResultMsgEnum.SAVE_FAIL.code(),message);
			}
			String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
			return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
		} catch (ParentNotFoundException e){
            String message = messageSource.getMessage(ResultMsgEnum.PARENT_NOT_FOUND.getKey(),new Object[]{}, request.getLocale());
            logger.warn(message,e.getMessage());
			return Result.error(ResultMsgEnum.PARENT_NOT_FOUND.code(),message);
		} catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
	}

    /**
     *删除
     * @param id 资源id
     * @param request HttpServletRequest
     * @return Result
     */
	@ResponseBody
	@RequestMapping(value="delete",method = RequestMethod.DELETE)
	@MethodName(value="博客管理->博客类目管理->删除资源",type=2)
	public Result deleteBlogCategory(Long id, HttpServletRequest request){

        try {
            if (StringUtils.isEmpty(id)) {
				String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
            }
            int deleteCount = blogCategoryService.deleteBlogCategory(id);
            if(deleteCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.DELETE_FAIL.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.DELETE_FAIL.code(),message);
            }
        } catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
        }
		String message = messageSource.getMessage(ResultMsgEnum.DELETE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.DELETE_SUCCESS.code(),message);
	}
}
